package com.xmz.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xmz.client.OrderClient;
import com.xmz.entity.Order;
import com.xmz.entity.User;
import com.xmz.mapper.UserMapper;
import com.xmz.service.IUserService;
import com.xmz.util.PageResult;
import com.xmz.util.Result;
import com.xmz.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderClient orderClient;
    @Override
    public PageResult<User> loadList(Integer pageNo, Integer pageSize, UserVo UserVo){
        PageResult<User> pageResult = new PageResult<>();
        QueryWrapper<User> query = new QueryWrapper<>();
        if(UserVo != null){
            query.like(StrUtil.isNotBlank(UserVo.getName()),"name",UserVo.getName())
                    .eq(StrUtil.isNotBlank(UserVo.getPhone()),"phone",UserVo.getPhone())
                    .eq(UserVo.getAge() !=null,"age",UserVo.getAge());
        }
        IPage<User> page = new Page<>(pageNo,pageSize);
        IPage<User> result = userMapper.selectPage(page,query);
        List<User> records = result.getRecords();
        pageResult.setRows(records);
        pageResult.setTotal(result.getTotal());
        return  pageResult;
    }

//    添加用户同时添加订单
    @Override
    public int addUser(UserVo userVo) {
        User user = new User();
        Order order = new Order();
        user.setName(userVo.getName());
        user.setAge(userVo.getAge());
        user.setPhone(userVo.getPhone());
        int i = userMapper.insert(user);
        if(i < 1) return  0;

        order.setUserId(user.getId());
        order.setName(userVo.getOrderName());
        order.setPrice(userVo.getPrice());
        order.setState(userVo.getState());
        order.setCount(userVo.getCount());
        Result result = orderClient.addOrder(order);
        if(result.getCode() != 200){
            throw new RuntimeException();
        }
        return 1;
    }
    @Override
    public int deleteUser(List<Integer> id) {
        return  userMapper.deleteBatchIds(id);
    }
    @Override
    public int updateUser(User User) {
        return userMapper.updateById(User);
    }
}
